﻿using AutoMapper;
using MediatR;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;
using RBAC_Class.Read.API.Application.Command.Roles;
using RBAC_Class.Read.API.Dto;

namespace RBAC_Class.Read.API.Application.CommandHandler.Roles
{
    public class RoleQueryCommandHandler:IRequestHandler<RoleQueryCommand,APIResult<APIPaging<List<RoleDto>>>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly IBaseRepository<RolePermission> rolePermissionRep;
        private readonly IBaseRepository<Permission> permissionRep;
        private readonly IMapper mapper;
        private readonly ILogger<RoleQueryCommandHandler> logger;

        public RoleQueryCommandHandler(IBaseRepository<Role> roleRep, IBaseRepository<RolePermission> rolePermissionRep, IBaseRepository<Permission> permissionRep,IMapper mapper, ILogger<RoleQueryCommandHandler> logger)
        {
            this.roleRep = roleRep;
            this.rolePermissionRep = rolePermissionRep;
            this.permissionRep = permissionRep;
            this.mapper = mapper;
            this.logger = logger;
        }

        public Task<APIResult<APIPaging<List<RoleDto>>>> Handle(RoleQueryCommand request, CancellationToken cancellationToken)
        {

            try
            {
                var list = roleRep.GetAll().Where(x => x.IsDelete == false);
                if (!string.IsNullOrEmpty(request.RoleName))
                {
                    list = list.Where(x => x.RoleName.Contains(request.RoleName));
                }
                var totalCount = list.Count();
                var totalPage = (int)Math.Ceiling(totalCount * 1.0 / request.PageSize);
                list = list.OrderBy(x => x.RoleID).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
                var data = mapper.Map<List<RoleDto>>(list);
                foreach (var item in data)
                {
                    var permissionId = rolePermissionRep.GetAll().Where(x => x.RoleID == item.RoleID && x.IsDelete == false).Select(x => x.PermissionID).ToList();
                    item.permissionID = permissionId;
                    item.PermissionName = permissionRep.GetAll().Where(x => permissionId.Contains(x.PermissionID)).Select(x => x.PermissionName).ToList();
                }
                return Task.FromResult(new APIResult<APIPaging<List<RoleDto>>>
                {
                    Code = ResultCode.Success,
                    Message = "查询成功",
                    Data = new APIPaging<List<RoleDto>>
                    {
                        TotalCount = totalCount,
                        TotalPage = totalPage,
                        Data = data
                    }
                });
            }
            catch (Exception ex)
            {
                logger.LogError("查询出错", ex);
                throw;
            }
            
        }
    }
}
